package lobby; // Always use packages. Never use default package.

import java.io.*; 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

/** Very simplistic servlet that generates plain text.
 *  Uses the @WebServlet annotation that is supported by
 *  Tomcat 7 and other servlet 3.0 containers. 
 */

@WebServlet("/lobby")
public class Lobby extends HttpServlet {
  private JSONArray queue = new JSONArray();
  private void appendQueue(String kirje)
  {
	  queue.add(kirje);
  }
  private void removeQueue(String kirje)
  {
	  queue.remove(kirje);
  }
  public String toJson(ArrayList<String> input) {
		JSONObject json = new JSONObject();
		for(int i=0;i<(input.size());i=i+2){
			json.put(input.get(i),input.get(i+1));
		}
		return json.toJSONString();
  }
  @Override
  
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("players", queue);
    out.print(jsonObj.toJSONString());
    out.flush();
    
  }
  public void doPost(HttpServletRequest request,
		  			 HttpServletResponse response)
  	  throws ServletException, IOException {
	  Integer status = Integer.parseInt(request.getParameter("Status"));
	  String name = request.getParameter("Name");
	//Status: 1- join queue,  0 - leave queue
	  if (status==0)
	  {
		  removeQueue(name);
		  
	  }
	  else
	  {
		  appendQueue(name);
	  }
  }
  
  					
}
